package ca.lscs.web.service;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

/**
 * @author Steve Pennington
 *
 */
@Controller
public class WeatherController {

	@RequestMapping("/ajax/weather")
	public void getWeather(@RequestParam(value="location", required=true) String location, HttpServletResponse response) throws IOException {
		URLFetchService service = URLFetchServiceFactory.getURLFetchService();
		String encodedLocation = URLEncoder.encode(location, "UTF-8");
		HTTPRequest weatherRequest = new HTTPRequest(new URL("http://www.google.com/ig/api?weather=" + encodedLocation));
		HTTPResponse weatherResponse = service.fetch(weatherRequest);
		byte[] responseData = weatherResponse.getContent();
		
		response.setContentType("text/xml");
		response.getOutputStream().write(responseData);
	}
}
